<template>
    <div class="app-container">
        <div class="top-content">
            <div
                v-for="(item, index) in dateList"
                :key="item" class="btnList"
                @click="checkDate(item, index)"
                :class="index == btnDateIndex ? 'selectBtn' : ''">
                {{ item.label }}
            </div>
        </div>
        <div class="card-list">
            <el-card v-for="(item, index) in cardList" :key="index+'cardList'" @click="checkCard(item,index)" :class="index == CardDateIndex ? 'selectcard' : ''">
                <el-row>
                    <el-col :span="10">
                        <div class="card-img">
                            <img :src="item.img" alt="">
                        </div>
                    </el-col>
                    <el-col :span="14">
                        <div class="card-information">
                            <div>{{ item.title }}</div>
                            <div class="card-data">{{ item.data }}</div>
                        </div>
                    </el-col>
                </el-row>
            </el-card>
        </div>
        <div id="chart" style="width: 100%;height:500px;margin-top: 20px;" v-loading="loading"></div>
    </div>
</template>
<script setup>
import * as echarts from 'echarts';
import { getCard, getChart } from '@/api/index.js';
import carFlow from '@/assets/icons/svg/carFlow.svg';
import customerFlow from '@/assets/icons/svg/customerFlow.svg';
import customerSale from '@/assets/icons/svg/customerSale.svg';
import customerOrder from '@/assets/icons/svg/customerOrder.svg';

const loading = ref(false)
const btnDateIndex = ref(0)
const CardDateIndex = ref(0)
const dateList = ref(
    [
        {
            label: '日',
            value: 'day'
        },{
            label: '月',
            value: 'month'
        },{
            label: '年',
            value: 'year'
        }
    ]
)
const cardList = ref(
    [
        {
            img: carFlow,
            title: '今日车流',
            data: '-',
            type: 'carFlow'
        }, {
            img: customerFlow,
            title: '今日客流',
            data: '-',
            type: 'customerFlow'
        }, {
            img: customerSale,
            title: '今日营业额',
            data: '-',
            type: 'customerSale'
        }, {
            img: customerOrder,
            title: '今日成交数',
            data: '-',
            type: 'customerOrder'
        }
    ]
)
const type = ref('day')
const cardType = ref('carFlow')

onMounted(() => {
    getCardData()
    getChartsData()
});

function checkCard(item, index){
    cardType.value = item.type;
    CardDateIndex.value = index;
    getChartsData()
}
// 获取卡片数据
function getCardData(){
    getCard().then(res=>{
        cardList.value = [
            {
                img: carFlow,
                title: '今日车流',
                data: res.data.carNum.toLocaleString() || '-',
                type: 'carFlow'
            }, {
                img: customerFlow,
                title: '今日客流',
                data: res.data.customerNum.toLocaleString() || '-',
                type: 'customerFlow'
            }, {
                img: customerSale,
                title: '今日营业额',
                data: `￥${res.data.saleAmount.toLocaleString() || '-'}`,
                type: 'customerSale'
            }, {
                img: customerOrder,
                title: '今日成交数',
                data: res.data.orderNum.toLocaleString() || '-',
                type: 'customerOrder'
            }
        ]
    })
}
// 切换日期
function checkDate (item, index) {
    type.value = item.value;
    btnDateIndex.value = index;
    getChartsData()
}
// 补齐日期方法(30日)
function generateDates(startDateStr, length) {
  const startDate = new Date(startDateStr);
  const dates = [];
  for (let i = 0; i < length; i++) {
    const newDate = new Date(startDate);
    newDate.setDate(startDate.getDate() - i);
    const year = newDate.getFullYear();
    const month = (newDate.getMonth() + 1).toString().padStart(2, '0');
    const day = newDate.getDate().toString().padStart(2, '0');
    dates.push(`${year}-${month}-${day}`);
  }
  return dates;
}
// 补齐日期方法(12个月)
function generateMonths(startMonthStr, length) {
  const [startYear, startMonth] = startMonthStr.split('-').map(Number);
  const months = [];
  for (let i = 0; i < length; i++) {
    let year = startYear;
    let month = startMonth - i;
    if (month <= 0) {
      month += 12;
      year--;
    }
    months.push(`${year}-${month.toString().padStart(2, '0')}`);
  }
  return months;
}
// 补齐日期方法(4年)
function generateYears(startYearStr, length) {
  const startYear = Number(startYearStr);
  const years = [];
  for (let i = 0; i < length; i++) {
    years.push(startYear - i);
  }
  return years.map(year => year.toString());
}
// 图表
function getChartsData() {
    loading.value = true;
    let url = `/business/indexStatistic/statistic?type=${type.value}&target=${cardType.value}`
    getChart(url).then(res=>{
        if(res.data){
            // 补齐日期
            if(type.value == 'day' && res?.data?.length < 30) {
                const thirtyDaysDates = generateDates(res.data[0].visitDate, 30-res.data?.length+1);
                thirtyDaysDates.forEach((v,i)=>{
                    if(i > 0) {
                        res.data.unshift(
                            {
                                visitDate: v,
                                customerNum: null
                            }
                        )
                    }
                })
            } else if (type.value == 'month' && res.data?.length < 12) {
                const thirtyDaysDates = generateMonths(res.data[0].visitMonth, 12-res.data?.length+1)
                thirtyDaysDates.forEach((v,i)=>{
                    if(i > 0) {
                        res.data.unshift(
                            {
                                visitMonth: v,
                                customerNum: null
                            }
                        )
                    }
                })
            } else if (type.value == 'year' && res.data?.length < 4) {
                const thirtyDaysDates = generateYears(res.data[0].visitYear, 4-res.data?.length+1)
                thirtyDaysDates.forEach((v,i)=>{
                    if(i > 0) {
                        res.data.unshift(
                            {
                                visitYear: v,
                                customerNum: null
                            }
                        )
                    }
                })
            }
            let myEchart = echarts.init(document.getElementById('chart'));
            let option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: type.value == 'day' ? ['今日指标', '昨日指标', '上周同日指标'] : type.value == 'month' ? ['当月指标', '上月指标'] : ['今年指标', '去年指标'],
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: res.data.map(item=>{
                        return type.value == 'day' ? item.visitDate : type.value == 'month' ? item.visitMonth : item.visitYear
                    })
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: type.value == 'day' ? '今日指标' : type.value == 'month' ? '当月指标' : '今年指标',
                        type: 'line',
                        data: res.data.map(item=>{
                            return type.value == 'day' ? item.num1 : item.customerNum
                        })
                    },
                    {
                        name: type.value == 'day' ? '昨日指标' : type.value == 'month' ? '上月指标' : '去年指标',
                        type: 'line',
                        data: []
                    }
                ]
            }
            let seriesData = []
            for(let i = 0; i < res.data.length-1; i++) {
                seriesData.push(type.value == 'day' ? res.data[i]?.num1 : res.data[i]?.customerNum)
            }
            seriesData.unshift(
                {
                    date: res.data[0]?.visitDate,
                    customerNum: null
                }
            )
            option.series[1].data = seriesData
            if(type.value == 'day') {
                const lastWeek = res.data.map(item => item.num2);
                option.series[2] = {
                    name: '上周同日指标',
                    type: 'line',
                    data: lastWeek
                }
            }
            myEchart.setOption(option,true)
            loading.value = false;
            window.onresize = function () {
                myEchart.resize();
            };
        }
    })
}
</script>
<style lang="scss" scoped>
.top-content{
    display: flex;
    justify-content: start;
    .btnList {
        width: 70px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 5px;
        border: 1px solid #ddd;
        margin-right: 10px;
        cursor: pointer;
    }
    .selectBtn {
        background-color: #409efe;
        border: 1px solid #409efe;
        color: #fff;
    }
}
.card-list {
    display: flex;
    margin: 10px 0;
    // justify-content: space-between;
    // flex: 1;
    justify-content: space-between;
    ::v-deep {
        .el-card {
            width: 25%;
            margin: 5px 0;
            display: flex;
            cursor: pointer;
        }
        .el-card:nth-child(1) {
            margin-right: 10px;
        }
        .el-card:nth-child(2) {
            margin-right: 10px;
        }
        .el-card:nth-child(3) {
            margin-right: 10px;
        }
        .el-card__body {
            width: 100%;
        }
    }
    .card-img {
        width: 60px;
        height: 60px;
        border-radius: 5px;
        img{
            width: 60px;
            height: 60px;
        }
    }
    .card-information {
        line-height: 30px;
        .card-data {
            font-weight: 600;
            font-size: 22px;
        }
    }
    .selectcard{
        background-color: #409efe;
        border: 1px solid #409efe;
        color: #fff;
    }
}
</style>